package com.example.unruly_zhao.mopaide.main;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.example.unruly_zhao.mopaide.R;
import com.example.unruly_zhao.mopaide.base.Home_Viewpager_Adapter;
import com.example.unruly_zhao.mopaide.base.News_Adapter;
import com.example.unruly_zhao.mopaide.bean.Hotspot_Bean;
import com.example.unruly_zhao.mopaide.global.Constants;
import com.example.unruly_zhao.mopaide.lock_screen.LockscreenUtil;
import com.example.unruly_zhao.mopaide.lock_screen.PermissionActivity;
import com.example.unruly_zhao.mopaide.powermanager.Activity_Manage;
import com.example.unruly_zhao.mopaide.table.Activity_TabLayouyt;
import com.github.yoojia.qrcode.qrcode.QRCodeEncoder;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Unruly_Zhao on 2017/8/19.
 */

public class Activity_HomePage extends AppCompatActivity {


    private LayoutInflater mInflater = null;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mParams;
    private boolean mIsLockEnable = false;
    private boolean mIsSoftkeyEnable = false;
    private ImageView mErweima_image, mErweima_image2;
    String mDeviceID;
    private VideoView mLock_videoView;
    //private RecyclerView mLock_news;

    private RelativeLayout mRl_lock_id;
    private View mLockscreenView2 = null;
    private List<Hotspot_Bean.ResultBean.DataBean> mHotpost_data;
    private TextView mMTv_size;
    private ViewPager mLock_pager;
    private ListView mLock_news;
    private News_Adapter mNews_adapter;
    private Handler mHandler;

    //viewpager
    private List<ImageView> imgList;
    private ImageView[] bottomImages;
    private boolean isAuto = true;
    private boolean isTouch = false;
    private int currentIndex = 0;
    private LinearLayout mindicator;
    private int[] imgs = {R.drawable.imgs_wzry, R.drawable.imgs_bwlb, R.drawable.imgs_wzry,
            R.drawable.imgs_wzry, R.drawable.imgs_bwlb, R.drawable.imgs_wzry};
    private ViewPager mLock_viewpager;

    //manage

    long mLastTime = 0;
    long mCurTime = 0;
    private long[] mHits = new long[3]; // 两次点击2 三次点击new long[3]...

    //dialog
    private Button mLock_btn_cancel;
    private Button mLock_btn_into;
    private LinearLayout mLock_ll_dialog;
    private ImageView mLock_xingzuo;
    private ImageView mLock_merchant;
    private WebView mLock_hotspot;
    private LinearLayout mLl_dialog;
    private RelativeLayout mLl_dialog22;
    private ImageView mImageView;
    private LinearLayout mLl_dialog3;

    private WebSettings settings;
    private LinearLayout mZuoshangjiao;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * 隐藏软键盘
         */
        getWindow().getDecorView().setSystemUiVisibility(

                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        initState();
        initView();
        attachLockScreenView();

        // hideNavKey(this);
        Window window = getWindow();
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE;
        getWindow().setAttributes(params);

    }

    private void attachLockScreenView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent permissionActivityIntent = new Intent(this, PermissionActivity.class);

                permissionActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(permissionActivityIntent);

                LockscreenUtil.getInstance(this).getPermissionCheckSubject()
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {

                                        addLockScreenView();

                                    }
                                }
                        );
            } else {
                addLockScreenView();
            }
        } else {
            addLockScreenView();
        }

    }

    private void addLockScreenView() {
        if (null != mWindowManager && null != mLockscreenView2 && null != mParams) {

            mLockscreenView2.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    return false;

                }
            });

            // 判断父布局是否存在
            if (mLockscreenView2.getParent() == null) {

                mWindowManager.addView(mLockscreenView2, mParams);
                settingLockView();

            }
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        if (null == mInflater) { //如果布局填空器为空 ，创建系统自带的
            mInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        if (null == mLockscreenView2) {  //如果视图为空创建视图管理找到视图

            mLockscreenView2 = mInflater.inflate(R.layout.view_locokscreen, null);  // 原版本的

        }
    }

    private void initState() {

        mIsLockEnable = LockscreenUtil.getInstance(this).isStandardKeyguardState();

        if (mIsLockEnable) {
            //WindowManager.LayoutParams 是 WindowManager 接口的嵌套类；继承于 ViewGroup.LayoutParams
            mParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT, //匹配父类
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,//系统内部错误提示，显示于所有内容之上。
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, // 不许获得焦点。
                    PixelFormat.TRANSLUCENT);  //设置为透明
        } else {
            mParams = new WindowManager.LayoutParams(
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.TYPE_PHONE,
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE  // 不可聚焦
                            | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                            | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD,

                    PixelFormat.TRANSLUCENT);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mIsLockEnable && mIsSoftkeyEnable) {
                mParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; //半透明
            } else {
                mParams.flags = WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS; // 背景图片
            }
        } else {
            mParams.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        }

        if (null == mWindowManager) {
            // Context.getSystemService(Context.WINDOW_SERVICE) 来获取WindowManager
            mWindowManager = ((WindowManager) this.getSystemService(WINDOW_SERVICE)); // 获取系统服务

        }
    }

    private void settingLockView() {
        mZuoshangjiao = (LinearLayout) mLockscreenView2.findViewById(R.id.lock_ll_zuoshangjao);
        // view_lockscreen 布局
        mRl_lock_id = (RelativeLayout) mLockscreenView2.findViewById(R.id.rl_lock_id);
        // LinearLayout 弹出dialog
        mLl_dialog = (LinearLayout) mLockscreenView2.findViewById(R.id.ll_dialig);
        // 二维码图片
        mErweima_image = (ImageView) mLockscreenView2.findViewById(R.id.lock_iv_erweima);
        // 二维码图片2
        mErweima_image2 = (ImageView) mLockscreenView2.findViewById(R.id.lock_iv_erweima2);
        // 视屏播放
        mLock_videoView = (VideoView) mLockscreenView2.findViewById(R.id.vv_lock_video);
        // 星座运势
        mLock_xingzuo = (ImageView) mLockscreenView2.findViewById(R.id.image_lock_yunshi);
        //mLock_xingzuo.loadUrl("http://astro.sina.com.cn/fate_day_Shu/");
        // 商家展示
        mLock_merchant = (ImageView) mLockscreenView2.findViewById(R.id.image_lock_merchant);
        //mLock_merchant.loadUrl("http://www.dianping.com/shop/78018478");
        // 新闻资讯
        // mLock_news = (ListView) mLockscreenView2.findViewById(R.id.lv_lock_news);
        // 热点指数
        mLock_hotspot = (WebView) mLockscreenView2.findViewById(R.id.wv_lock_hotspot);

        settings = mLock_hotspot.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setAllowFileAccess(true);
        settings.setLoadWithOverviewMode(true);
        //settings.setUseWideViewPort(true);
        //settings.setDatabaseEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setDefaultTextEncodingName("UTF-8");

        mLock_hotspot.loadUrl("http://top.baidu.com/clip?b" +
                "=1&hd_h_info=1&col=2&hd_h=1&hd_meshline=0&hd_border=0" +
                "&hd_searches=0&hd_search=1&hd_trend=1");



        // TODO 最好的方法就是 swich  通过swich实现所有控件点击事件

        // 生成二维码
        setDeviceImag();
        //初始化VideoView
        initVideoView();
        // 跳转抽奖界面
        intentlotto();
        // 跳转商家界面
        intentmerchant();
        //跳转新闻界面
        //intentnews();
        //跳转热点指数
        intenthotspot();
        // 锁屏界面初始化新闻模块
        init_news();
        // 锁屏界面初始化热点资讯
        //init_Hostpot();
        // 图片轮播
        init_imgs();
        // 系统管理页面
        init_manage();
        //  弹出对话框  扫码进入
        initial_dialog();
    }

    //TODO   点击Webview 弹出一个dialog对话框  扫描进入菜单详情界面
    private void initial_dialog() {
        mLl_dialog3 = (LinearLayout) mLockscreenView2.findViewById(R.id.ll_dialog3);
        mLl_dialog22 = (RelativeLayout) mLockscreenView2.findViewById(R.id.ll_dialog2);
        mImageView = (ImageView) mLockscreenView2.findViewById(R.id.close);

        mLl_dialog3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mLl_dialog22.setVisibility(View.VISIBLE);
                mZuoshangjiao.setVisibility(View.GONE);


            }
        });

        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mLl_dialog22.setVisibility(View.GONE);
                mZuoshangjiao.setVisibility(View.VISIBLE);

            }
        });


    }

    //  图片轮播
    private void init_imgs() {

        mindicator = (LinearLayout) mLockscreenView2.findViewById(R.id.mindiator);
        // 广告轮播
        mLock_viewpager = (ViewPager) mLockscreenView2.findViewById(R.id.vp_lock_pager);
        initVp();
        initBottom();
        t.start();
    }

    /**
     * 初始化 轮播
     */

    private void initVp() {
        imgList = new ArrayList<ImageView>();
        for (int i = 0; i < imgs.length; i++) {
            ImageView img = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT + 10, ViewGroup.LayoutParams.MATCH_PARENT);
            img.setImageResource(imgs[i]);
            img.setLayoutParams(params);
            img.setScaleType(ImageView.ScaleType.FIT_XY); // 图片类型为填充状态
            imgList.add(img);
        }
        //  TODO 广告轮播跳转
        imgList.get(0).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Activity_HomePage.this, "1111111", Toast.LENGTH_LONG).show();

            }
        });
        imgList.get(1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Activity_HomePage.this, "2222222", Toast.LENGTH_LONG).show();

            }
        });
        imgList.get(2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Activity_HomePage.this, "333333333", Toast.LENGTH_LONG).show();

            }
        });
        imgList.get(3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Activity_HomePage.this, "44444444", Toast.LENGTH_LONG).show();

            }
        });
        imgList.get(4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Activity_HomePage.this, "5555555", Toast.LENGTH_LONG).show();

            }
        });
        imgList.get(5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(Activity_HomePage.this, "5555555", Toast.LENGTH_LONG).show();

            }
        });


        Home_Viewpager_Adapter adapter = new Home_Viewpager_Adapter(imgList);
        mLock_viewpager.setAdapter(adapter);
    }

    /**
     * 设置轮播 底部小圆点
     */
    private void initBottom() {

        bottomImages = new ImageView[imgList.size()];

        for (int j = 0; j < bottomImages.length; j++) {

            ImageView bottom = new ImageView(this);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    14, 14);

            params.setMargins(5, 10, 5, 10);

            bottom.setLayoutParams(params);

            if (j == 0) {
                bottom.setImageResource(R.drawable.xd_blue);
            } else {
                bottom.setImageResource(R.drawable.xd_white);
            }
            bottomImages[j] = bottom;

            mindicator.addView(bottom);
        }
        mLock_viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {

                // TODO Auto-generated method stub

                for (int i = 0; i < bottomImages.length; i++) {
                    int p = arg0 % imgList.size();
                    if (i == p) {
                        bottomImages[i].setImageResource(R.drawable.xd_blue);
                    } else {
                        bottomImages[i].setImageResource(R.drawable.xd_white);
                    }
                }

                currentIndex = arg0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub
                if (arg0 == ViewPager.SCROLL_STATE_IDLE) {
                    isTouch = false;
                } else {
                    isTouch = true;
                }
            }
        });

    }

    /**
     * 主界面广告轮播 3秒轮播
     */

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (isAuto) {
                try {
                    t.sleep(3000);
                    handler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    });
    private Handler handler = new Handler() {
        private int index = 0;
        private ImageView mImageView;
        private TextView mTextView;
        private List<Hotspot_Bean.ResultBean.DataBean> mMHotpost_data;

        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                if (isTouch) {
                    return;
                }
                currentIndex++;
                mLock_viewpager.setCurrentItem(currentIndex);
            } else if (msg.what == 1) {
                mMHotpost_data = (List<Hotspot_Bean.ResultBean.DataBean>) msg.obj;
                mTextView = (TextView) mLockscreenView2.findViewById(R.id.tv_lock_news_text);
                mImageView = (ImageView) mLockscreenView2.findViewById(R.id.iv_lock_news_imgs);
                mTextView.setText(mMHotpost_data.get(index).getTitle());
                Picasso.with(Activity_HomePage.this).load(mMHotpost_data.get(index).getThumbnail_pic_s()).into(mImageView);
                index++;
                handler.sendEmptyMessageDelayed(2, 100000);
            } else if (msg.what == 2) {
                mTextView.setText(mMHotpost_data.get(index).getTitle());
                Picasso.with(Activity_HomePage.this).load(mMHotpost_data.get(index).getThumbnail_pic_s()).into(mImageView);
                if (index >= mMHotpost_data.size()) {
                    index = 0;
                    handler.sendEmptyMessageDelayed(2, 1000 * 60 * 5);
                } else {
                    index++;
                    handler.sendEmptyMessageDelayed(2, 1000 * 60 * 5);
                }

            }
        }
    };

    protected void onDestroy() {
        super.onDestroy();

        Logger.d("==============");

        isAuto = false;
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            Logger.e("==============");
        }
    }

    /**
     * 新闻资讯
     */
    private void init_news() {

        //热点指数
        String hostpot_url = "http://v.juhe.cn/toutiao/index?type=top&key=2d222092ba994e3a928d46d83f097c8b";

        OkGo.get(hostpot_url)
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Gson gson = new Gson(); //Gson解析工具

                        Hotspot_Bean hotspot_bean = gson.fromJson(s, Hotspot_Bean.class); // 通过gson.from 取出Bean的值

                        // 取出Data的集合
                        mHotpost_data = hotspot_bean.getResult().getData();

                        Message msg = handler.obtainMessage();

                        msg.what = 1;

                        msg.obj = mHotpost_data;

                        handler.sendMessage(msg);

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });

    }

    Runnable runnable = new Runnable() {  // 创建一个Runble对象
        @Override
        public void run() {

            // TODO Auto-generated method stub

            //要做的事情，这里再次调用此Runnable对象，以实现每两秒实现一次的定时器操作

          /*  if (mHotpost_data.size() > 0){
                mHotpost_data.clear();
            }
            List list = new ArrayList();

            list.addAll(mHotpost_data);*/

            mNews_adapter.notifyDataSetChanged();  //通知适配器更新

            mHandler.postDelayed(this, 5000);  // 2秒后通知适配器更改


        }
    };

    /**
     * 跳转热点指数模块
     */
    private void intenthotspot() {


        mLock_hotspot.setWebViewClient(new WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                Intent hotspot = new Intent(Activity_HomePage.this, Activity_Hotspot.class);

                startActivity(hotspot);

                finish();

                Toast.makeText(Activity_HomePage.this,"跳转成功",Toast.LENGTH_LONG).show();

                return true;
            }
        });
    }

    /**
     * 热点资讯
     */
    private void init_Hostpot() {

      /*  //热点指数
        String hostpot_url = "http://v.juhe.cn/toutiao/index?type=top&key=2d222092ba994e3a928d46d83f097c8b";

        OkGo.get(hostpot_url)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Gson gson = new Gson(); //Gson解析工具

                        Hotspot_Bean hotspot_bean = gson.fromJson(s, Hotspot_Bean.class); // 通过gson.from 取出Bean的值

                        // 取出Data的集合
                        mHotpost_data = hotspot_bean.getResult().getData();

                        GridLayoutManager hotpost = new GridLayoutManager(Activity_HomePage.this, 2);

                        mLock_hotspot.setLayoutManager(hotpost);

                       *//* Hotpost_Adapter hotpost_adapter = new Hotpost_Adapter(Activity_HomePage.this,mHotpost_data);

                        mLock_hotspot.setAdapter(hotpost_adapter);*//*
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });*/


    }


    /**
     * 跳转商家模块
     */
    private void intentmerchant() {

        mLock_merchant.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                mRl_lock_id.setVisibility(View.GONE);  // 设置布局隐藏

                Intent merchant = new Intent(Activity_HomePage.this, Activity_Merchant.class);

                startActivity(merchant);

                finish();
            }
        });
    }


    /**
     * 跳转抽奖模块
     */
    private void intentlotto() {

        mLock_xingzuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mRl_lock_id.setVisibility(View.GONE);

                Intent lotto = new Intent(Activity_HomePage.this, Activity_Lotto.class);

                startActivity(lotto);

                finish();

            }
        });

    }


    /**
     * 初始化视屏
     */

    private void initVideoView() {

        mLock_videoView.setEnabled(false);

       /* //设置视频控制器
        mVideoView.setMediaController(new MediaController(this));*/

        String videoFilePath = Constants.FILE_PATH + "video.mp4";

        Uri videoUri = Uri.parse(videoFilePath);

        mLock_videoView.setVideoURI(videoUri);

        mLock_videoView.start();

        //设置视频路径
        mLock_videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer video) {
                // TODO Auto-generated method stub

                video.start();

                video.setLooping(true); //视屏一直播放
            }
        });

    }


    /**
     * 初始化二维码
     */
    private void setDeviceImag() {

        final WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);

        final Display display = manager.getDefaultDisplay();

        Point displaySize = new Point();

        display.getSize(displaySize);

        final int size = Math.min(displaySize.x, displaySize.y);

        generateQRCode(size);

    }

    /**
     * 生成二维码
     *
     * @param size
     */

    private void generateQRCode(final int size) {


        mDeviceID = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);

        Observable.just("http://pb.en8848.com/mqtt/PhpMQTTClient-master/mpadsend.php?device=" + mDeviceID)

                .map(new Func1<String, Bitmap>() {
                    @Override
                    public Bitmap call(String content) {

                        final Bitmap centerImage = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);

                        return new QRCodeEncoder.Builder()
                                .width(size)
                                .height(size)
                                .paddingPx(0)
                                .marginPt(3)
                                .centerImage(centerImage)
                                .build()
                                .encode(content);
                    }
                })
                .subscribeOn(Schedulers.computation())

                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Action1<Bitmap>() {
                    @Override
                    public void call(Bitmap bitmap) {

                        mErweima_image.setImageBitmap(bitmap);

                        mErweima_image2.setImageBitmap(bitmap);


                    }
                });

    }


    /**
     * 调用广播
     */
    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver();
    }

    //注册广播
    public void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("zzq");
        registerReceiver(mReceiver, intentFilter);
    }


    //接收广播
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            Logger.addLogAdapter(new AndroidLogAdapter());

            Logger.i(action);  // TODO

            if (action.equals("zzq")) {

                String url = "unlock";

                String stringExtra = intent.getStringExtra("msg");

                Logger.i(url);  // TODO
                Logger.i(stringExtra);  // TODO

                if (url.equals(stringExtra)) {

                    Intent meun = new Intent(Activity_HomePage.this, Activity_TabLayouyt.class);

                    startActivity(meun);

                    finish();

                }

            }
        }
    };

    private void init_manage() {


        mErweima_image.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);

                mHits[mHits.length - 1] = SystemClock.uptimeMillis(); // 系统开机时间

                if (mHits[0] >= (SystemClock.uptimeMillis() - 500)) {

                    mLock_ll_dialog = (LinearLayout) mLockscreenView2.findViewById(R.id.ll_lock_dialog);
                    mLock_ll_dialog.setVisibility(View.VISIBLE);
                    mLock_btn_cancel = (Button) mLockscreenView2.findViewById(R.id.negativeButton);
                    mLock_btn_into = (Button) mLockscreenView2.findViewById(R.id.positiveButton);

                    init_into();  //进入管理界面

                    init_cancel();  // 取消按钮

                    Toast.makeText(Activity_HomePage.this, "这就是传说中的三击事件", Toast.LENGTH_LONG).show();
                }
            }

        });
    }


    private void init_cancel() {
        mLock_btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mLock_ll_dialog.setVisibility(View.GONE);

                Toast.makeText(Activity_HomePage.this, "取消进入", Toast.LENGTH_LONG).show();

            }
        });
    }

    private void init_into() {
        mLock_btn_into.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mLock_ll_dialog.setVisibility(View.GONE);

                //TODO 跳转其他界面可以  但是不能跳转到Activity_Manage
                // 管理界面
                Intent into = new Intent(Activity_HomePage.this, Activity_Manage.class);

                startActivity(into);

                finish();

                Toast.makeText(Activity_HomePage.this, "进入管理界面", Toast.LENGTH_LONG).show();

            }
        });

    }


    /**
     * 隐藏虚拟键
     */
    // TODO
  /*  private void hideSystemUI() {

        View decorView = getWindow().getDecorView();

        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

        decorView.setSystemUiVisibility(uiOptions);
    }*/


    /**
     * 友盟统计
     */

    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }


    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;

            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 设置为横屏
     */

    @Override
    protected void onResume() {

        super.onResume();

        MobclickAgent.onResume(this);

        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }


}
